package com.aibaixun.system.service.impl;

import com.aibaixun.common.core.domain.R;
import com.aibaixun.common.exception.ServiceException;
import com.aibaixun.common.utils.file.FileUploadUtils;
import com.aibaixun.common.utils.file.FileUtils;
import com.aibaixun.system.domain.SysFile;
import com.aibaixun.system.service.SysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;

/**
 * 本地文件存储
 *
 * @author qihong
 */
@Primary
@Service
public class SysFileServiceImpl implements SysFileService
{
    private static final Logger logger = LoggerFactory.getLogger(SysFileServiceImpl.class);

    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String filePrefix;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.basePath}")
    private String basePath;

    @Override
    public R uploadFile(MultipartFile file) {
        if(file == null){
            throw new ServiceException("文件不能为空");
        }
        try{
            String uploadpath = LocalDate.now().toString();
            String name = FileUploadUtils.upload(basePath, uploadpath, file, null, null);
            SysFile sysFile = new SysFile();
            sysFile.setUrl(filePrefix + name);
            sysFile.setName(FileUtils.getName(name));
            return R.ok(sysFile);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("文件上传失败："+e.getMessage());
            throw new ServiceException("文件上传失败："+e.getMessage());
        }
    }

}
